pacman::p_load(tmap, sf, sfdep, tidyverse, DT, leaflet, stplanr )Take-home Exercise 2
0. Goals & Objectives.
Our goal is to conduct a case study to demonstrate the potential value of Geospatial Data Science & Analysis, by integrating publicly available data from multiple sources to build a spatial interaction models, to determine factors affecting urban mobility patterns of public bus transit.
Recentdeployments of massively pervasive computing technologies such as in-vehicle GPS and SMART cards by public transport provide plenty of data for tracking movement patterns through space and time, but the explosive growth of data has outstripped public services’ ability to utilise, transform, and understand the data.
More detail about the task from: https://isss624-ay2023-24nov.netlify.app/take-home_ex02
Modifible Areal Unit Problem (MAUP): - MPSZ is too coarse, too huge a subzone area; people may live only in a corner of the subzone - Planning subzones too large, so we use analytical hexagon
“Map is not interesting, pattern revealed by and factors affecting the map is interesting. Can we explain this by building a spatial model?” - Building a model to explain flows; Spatial Interaction Model
GLM: Generalised Linear-Regression Model (over linear model):
- Dwelling Units as proxy for population;
- Can compare HDB-only VS dwelling units vs room-flat vs 1/2/3/ room flat unit
- POI: points of interest name & type
Due to the nature of EDA and Data Analysis, parts of this page have been Collapsed or placed behind tabs, to avoid excessive scrolling.
For easier reading, this study is also presented in point-form.
0.1 Dataset used
0.1.1 Aspatial Dataset
| Dataset, Purpose & Source: | Key columns |
|---|---|
Via data.gov |
|
Via LTA DataMall |
|
0.1.2 Geospatial Dataset
| Filename, Purpose & Source: | Key columns |
|---|---|
Via data.gov |
|
Via LTA DataMall |
|
1. Geospatial Data Wrangling
This study was performed in R, written in R Studio, and published using Quarto.
1.1 Import Packages
This function calls pacman to load sf, tidyverse, tmap, knitr packages;
tmap: For thematic mapping; powerful mapping package;sf: for geospatial data handling, but also geoprocessing: buffer, point-in-polygon count, etc;sfdep: useful functions for creating weight matrix, LISA calculations etc;tidyverse: for non-spatial data handling; commonly used R package and containsdplyrfor dataframe manipulation andggplotfor data visualization;DT: for displaying datatables;leaflet: for custom layer controls overtmapvisualisations.stplanar: for creating desire lines to visualize O/D flows
1.2 Import Geospatial Data
1.2.1 raw_bus_stop_sf: Load Geospatial Bus Stop Data
- First, we load
BusStopshapefile data from LTA Datamall; st_read()is used to import the ESRI Shapefile data into ansfdataframe.- From previous take-home exercise, we know BusStop has the incorrect CRS (coordinate reference system), as EPSG 9001 instead of 3414, so we use
st_set_crs()to correct this - We use
head()to preview the first 6 rows
- From previous take-home exercise, we know BusStop has the incorrect CRS (coordinate reference system), as EPSG 9001 instead of 3414, so we use
show code
raw_bus_stop_sf <- st_read(dsn = "data/geospatial",
layer = "BusStop") %>%
st_set_crs(3414)Reading layer `BusStop' from data source
`C:\1darren\ISSS624\Take-home_Ex02\data\geospatial' using driver `ESRI Shapefile'
Simple feature collection with 5161 features and 3 fields
Geometry type: POINT
Dimension: XY
Bounding box: xmin: 3970.122 ymin: 26482.1 xmax: 48284.56 ymax: 52983.82
Projected CRS: SVY21
Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
that
show code
head(raw_bus_stop_sf)Simple feature collection with 6 features and 3 fields
Geometry type: POINT
Dimension: XY
Bounding box: xmin: 13228.59 ymin: 30391.85 xmax: 41603.76 ymax: 44206.38
Projected CRS: SVY21 / Singapore TM
BUS_STOP_N BUS_ROOF_N LOC_DESC geometry
1 22069 B06 OPP CEVA LOGISTICS POINT (13576.31 32883.65)
2 32071 B23 AFT TRACK 13 POINT (13228.59 44206.38)
3 44331 B01 BLK 239 POINT (21045.1 40242.08)
4 96081 B05 GRACE INDEPENDENT CH POINT (41603.76 35413.11)
5 11561 B05 BLK 166 POINT (24568.74 30391.85)
6 66191 B03 AFT CORFE PL POINT (30951.58 38079.61)
- We check the coordinate reference system with
st_crs(); and see that it is now indeed correctly set to 3414:
st_crsReadout
show code
st_crs(raw_bus_stop_sf)Coordinate Reference System:
User input: EPSG:3414
wkt:
PROJCRS["SVY21 / Singapore TM",
BASEGEOGCRS["SVY21",
DATUM["SVY21",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
ID["EPSG",4757]],
CONVERSION["Singapore Transverse Mercator",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",1.36666666666667,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",103.833333333333,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",1,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",28001.642,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",38744.572,
LENGTHUNIT["metre",1],
ID["EPSG",8807]]],
CS[Cartesian,2],
AXIS["northing (N)",north,
ORDER[1],
LENGTHUNIT["metre",1]],
AXIS["easting (E)",east,
ORDER[2],
LENGTHUNIT["metre",1]],
USAGE[
SCOPE["Cadastre, engineering survey, topographic mapping."],
AREA["Singapore - onshore and offshore."],
BBOX[1.13,103.59,1.47,104.07]],
ID["EPSG",3414]]
- We use
qtm()to perform a quick visualization of the various bus stops:
show code
tmap_mode("plot")tmap mode set to plotting
show code
qtm(raw_bus_stop_sf)
1.2.2 mpsz_sf: Visualizing Singapore’s Master Plan 2019 Subzone Boundaries
We now load Master Plan 2019 Subzone Boundary
Next, we load
MPSZ-2019shapefile data from Data.gov.sg, comprising Master Plan 2019 Subzone Boundary (No Sea) data ;st_read()is used to import the ESRI Shapefile data into ansfdataframe;- We use
st_crs()to check the Coordinate Reference System (CRS);
- We use
show code
mpsz_sf <- st_read(dsn = "data/geospatial",
layer = "MPSZ-2019") Reading layer `MPSZ-2019' from data source
`C:\1darren\ISSS624\Take-home_Ex02\data\geospatial' using driver `ESRI Shapefile'
Simple feature collection with 332 features and 6 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: 103.6057 ymin: 1.158699 xmax: 104.0885 ymax: 1.470775
Geodetic CRS: WGS 84
show code
st_crs(mpsz_sf)Coordinate Reference System:
User input: WGS 84
wkt:
GEOGCRS["WGS 84",
DATUM["World Geodetic System 1984",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
CS[ellipsoidal,2],
AXIS["latitude",north,
ORDER[1],
ANGLEUNIT["degree",0.0174532925199433]],
AXIS["longitude",east,
ORDER[2],
ANGLEUNIT["degree",0.0174532925199433]],
ID["EPSG",4326]]
- We see that
MPSZ-2019is set to WGS 84/EPSG 4326 projection, which is inconsistent with the rest of our dataset; - Thus, we use
st_transform()to reproject the data to SVY21/EPSG 3414 Coordinate Reference System (CRS) to ensure consistent distance calculation:
show code
mpsz_sf <- mpsz_sf %>%
st_transform(crs=3414)
st_crs(mpsz_sf)Coordinate Reference System:
User input: EPSG:3414
wkt:
PROJCRS["SVY21 / Singapore TM",
BASEGEOGCRS["SVY21",
DATUM["SVY21",
ELLIPSOID["WGS 84",6378137,298.257223563,
LENGTHUNIT["metre",1]]],
PRIMEM["Greenwich",0,
ANGLEUNIT["degree",0.0174532925199433]],
ID["EPSG",4757]],
CONVERSION["Singapore Transverse Mercator",
METHOD["Transverse Mercator",
ID["EPSG",9807]],
PARAMETER["Latitude of natural origin",1.36666666666667,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8801]],
PARAMETER["Longitude of natural origin",103.833333333333,
ANGLEUNIT["degree",0.0174532925199433],
ID["EPSG",8802]],
PARAMETER["Scale factor at natural origin",1,
SCALEUNIT["unity",1],
ID["EPSG",8805]],
PARAMETER["False easting",28001.642,
LENGTHUNIT["metre",1],
ID["EPSG",8806]],
PARAMETER["False northing",38744.572,
LENGTHUNIT["metre",1],
ID["EPSG",8807]]],
CS[Cartesian,2],
AXIS["northing (N)",north,
ORDER[1],
LENGTHUNIT["metre",1]],
AXIS["easting (E)",east,
ORDER[2],
LENGTHUNIT["metre",1]],
USAGE[
SCOPE["Cadastre, engineering survey, topographic mapping."],
AREA["Singapore - onshore and offshore."],
BBOX[1.13,103.59,1.47,104.07]],
ID["EPSG",3414]]
- Now, let’s visualize the bus stop within the
mpszsubzone boundaries; - We set
tmap_mode("plot")to allow us to scroll; - We use
tm_shape() + tm_polygons()to map a base layer of thempszboundaries;- On top of which, we layer
tm_shape() + tm_dots()to show the bus stops.
- On top of which, we layer
show code
tmap_mode("plot")tmap mode set to plotting
show code
tmap_options(check.and.fix = TRUE)
tm_shape(mpsz_sf) +
tm_polygons() +
tm_shape(raw_bus_stop_sf) +
tm_dots()Warning: The shape mpsz_sf is invalid. See sf::st_is_valid

- We note there are a number of bus stops outside Singapore’s boundaries; Specifically, three bus stops in a cluster just outside the Causeway, and one further North.
- We perform several steps to isolate & check the data;
- we use
st_filter()to find bus stops within Singapore’s Administrative National Boundaries, and createsg_bus_stop_sffor future use. - to check what bus stops have been dropped, we use
anti_join()to compareraw_bus_stop_sfwithsg_bus_stop_sf. We usest_drop_geometryon bothsfdataframes to only compare the non-geometry columns.
- we use
show code
sg_bus_stop_sf <- st_filter(raw_bus_stop_sf, mpsz_sf)
anti_join(st_drop_geometry(raw_bus_stop_sf), st_drop_geometry(sg_bus_stop_sf))Joining with `by = join_by(BUS_STOP_N, BUS_ROOF_N, LOC_DESC)`
BUS_STOP_N BUS_ROOF_N LOC_DESC
1 47701 NIL JB SENTRAL
2 46239 NA LARKIN TER
3 46609 NA KOTARAYA II TER
4 46211 NIL JOHOR BAHRU CHECKPT
5 46219 NIL JOHOR BAHRU CHECKPT
- We see there are in fact 5 bus stops outside of Singapore (including the defunct Kotaraya II Terminal) that have been removed, which means our data cleaning was correct.
1.3 Geospatial Data Cleaning
1.3.1 Removing Duplicate Bus Stops
- From Take-home Exercise 1, we know that there are a number of repeated bus stops. We repeat some steps;
- We use
length()to find the total number of raw values in the$BUS_STOP_Ncolumn ofsg_bus_stop_sf;- We then compare this to
length(unique())to find the unique values;
- We then compare this to
- And, indeed, we find there are 16 bus stops that are repeated;
cat("\nResults before removing duplicates: \n=======================================================\n")
Results before removing duplicates:
=======================================================
cat("Total number of rows in sg_bus_stop_sf\t\t: ", paste0(length(sg_bus_stop_sf$BUS_STOP_N)))Total number of rows in sg_bus_stop_sf : 5156
cat("\nTotal unique bus stop IDs in sg_bus_stop_sf\t: ", paste0(length(unique(sg_bus_stop_sf$BUS_STOP_N))))
Total unique bus stop IDs in sg_bus_stop_sf : 5140
cat("\nRepeated bus stops\t\t\t\t: ", paste0(length(sg_bus_stop_sf$BUS_STOP_N) - length(unique(sg_bus_stop_sf$BUS_STOP_N))))
Repeated bus stops : 16
- It appears there are 16 datapoints that are specifically repeated; let’s remove them by deleting the duplicated rows:
- we use
duplicated()to identify rows with repeated values of$BUS_STOP_N; duplicated rows will returnTRUEwhile all other rows will returnFALSE - We use
!to invert the values, so only the unduplicated rows will returnTRUE. - We then use square brackets
[]to indexsg_bus_stop_sfbased on the rows, and return only the unduplicated rows; - We then assign the output using
<-intobus_stop_sf, for use.
- we use
show code
bus_stop_sf <- sg_bus_stop_sf[!duplicated(sg_bus_stop_sf$BUS_STOP_N), ]
head(bus_stop_sf)Simple feature collection with 6 features and 3 fields
Geometry type: POINT
Dimension: XY
Bounding box: xmin: 13228.59 ymin: 30391.85 xmax: 41603.76 ymax: 44206.38
Projected CRS: SVY21 / Singapore TM
BUS_STOP_N BUS_ROOF_N LOC_DESC geometry
1 22069 B06 OPP CEVA LOGISTICS POINT (13576.31 32883.65)
2 32071 B23 AFT TRACK 13 POINT (13228.59 44206.38)
3 44331 B01 BLK 239 POINT (21045.1 40242.08)
4 96081 B05 GRACE INDEPENDENT CH POINT (41603.76 35413.11)
5 11561 B05 BLK 166 POINT (24568.74 30391.85)
6 66191 B03 AFT CORFE PL POINT (30951.58 38079.61)
show code
cat("\nResults after removing duplicates: \n=======================================================\n")
Results after removing duplicates:
=======================================================
show code
cat("Total number of rows in bus_stop_sf\t\t: ", paste0(length(bus_stop_sf$BUS_STOP_N)))Total number of rows in bus_stop_sf : 5140
show code
cat("\nTotal unique bus stop IDs in bus_stop_sf\t: ", paste0(length(unique(bus_stop_sf$BUS_STOP_N))))
Total unique bus stop IDs in bus_stop_sf : 5140
show code
cat("\nRepeated bus stops\t\t\t\t: ", paste0(length(bus_stop_sf$BUS_STOP_N) - length(unique(bus_stop_sf$BUS_STOP_N))))
Repeated bus stops : 0
- We can do a quick check to visualize these;
- We use
tmap_mode("view")to allow us to scroll around and check that the bus stops fall within Singapore’s national boundaries, and set zoom limits to focus the attention - We combine
tm_shape()andtm_polygons()to map the master plan subzones in grey; - We combine
tm_shape()andtm_dots()to map locations of bus stops; for visual distinction with the grey zones, we use the “Spectral” palette
- We use
show code
tmap_mode("view")tmap mode set to interactive viewing
show code
tm_shape(mpsz_sf) +
tm_polygons() +
tm_shape(bus_stop_sf) +
tm_dots(col = "BUS_STOP_N", palette = "Spectral", legend.show = FALSE) +
tm_view(set.zoom.limits = c(11, 13))Warning: The shape mpsz_sf is invalid (after reprojection). See sf::st_is_valid
Warning: Number of levels of the variable "BUS_STOP_N" is 5140, which is larger
than max.categories (which is 30), so levels are combined. Set
tmap_options(max.categories = 5140) in the layer function to show all levels.
show code
tmap_mode("plot")tmap mode set to plotting
- Now, we can start preparing the hexagon map.
1.4 Generating Hexagon Maps
- We generate the hexagon map in three steps:
- We use
st_make_grid()withsquare = FALSEto create the hexagon layer as defined in the study, which we nameraw_hex_grid;- We pass
cellsize = 750to create the hexagons of necessary size. Prof Kam defined the apothem as 375m, as the Traffic Analysis Zone is typically 750m in size. - I used
units::as_unitsto pass 750 metres into the argument. I am still uncertain whether a length of 750m needs to be reprojected, or whether we need to do any further transformation. - We use
st_transform()just in case we need to reproject the coordinate system, just in case.
- We pass
- We use
st_sf()to convertraw_hex_gridinto ansfdataframe for further manipulation later; - However, trying to visualize this right now just gives us a map full of hexagons, so need to eliminate the empty hexagons; - We usemutate()to create a new column,$n_bus_stopsthat counts the number of bus stops in each hexagon usinglengths(st_intersects())st_intersects()gives us a list of bus stops in each hexagon, so we uselengths()to count the number
- We create our final
sfdataframe,hexagon_sfin two steps; - First, we usefilter()to select only hexagons with nonzero number of bus stops; - Then,mutate()is used here to create agrid_idcolumn, labelling only the hexagons with nonzero bus stops.
- Finally, we perform a quick plot to confirm that every bus stop is inside a hexagon;
- Using
hexagon_sfas our base layer, we usetmap_shape()andtm_polygons()to visualizes our hexes. We passpalette = "Spectral"for visual distinguishment against the black dots of the bus stops. - We use
tmap_shape()andtm_dots()to visualize our bus stop as black dots
- Using
show code
# STEP 1 - Create hexagon map
raw_hex_grid <- st_make_grid(bus_stop_sf, cellsize = units::as_units(375, "m"), what = "polygons", square = FALSE) %>%
st_transform(crs = 3414)
# STEP 2 - Convert to sf object and count the number of bus stops inside;
raw_hex_grid <- st_sf(raw_hex_grid) %>%
mutate(n_bus_stops = lengths(st_intersects(raw_hex_grid, sg_bus_stop_sf)))
# Count number of points in each grid, code snippet referenced from:
# https://gis.stackexchange.com/questions/323698/counting-points-in-polygons-with-sf-package-of-r
# STEP 3 - Filter for nonempty hexes and label:
hexagon_sf <- filter(raw_hex_grid, n_bus_stops > 0)
hexagon_sf <- hexagon_sf %>%
mutate(grid_id = 1:nrow(hexagon_sf)) %>%
select(grid_id, raw_hex_grid, n_bus_stops)
tmap_mode("plot")tmap mode set to plotting
show code
tm_shape(hexagon_sf) +
tm_polygons(col = "grid_id", palette = "Spectral", legend.show = FALSE) +
tm_shape(bus_stop_sf) +
tm_dots()
show code
tmap_mode("plot")tmap mode set to plotting
- We can visually confirm that every black dot is within a hexagon.
- We re-use a bit of code from Take-Home Exercise 1 to plot our analytical hexagons on a map of Singapore and visualize the number of bus stops in each hexagon:
show code
tmap_mode("view")tmap mode set to interactive viewing
show code
tm_basemap(providers$OneMapSG.Grey) +
tm_shape(hexagon_sf) +
tm_fill(
col = "n_bus_stops",
palette = "-plasma",
style = "cont",
breaks = c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
title = "Number of bus_stops",
id = "grid_id",
showNA = FALSE,
alpha = 0.6,
popup.vars = c(
"Number of Bus Stops: " = "n_bus_stops"
),
popup.format = list(
n_bus_stops = list(format = "f", digits = 0)
)
) +
tm_borders(col = "grey40", lwd = 0.7) +
tm_view(set.zoom.limits = c(11, 13))show code
tmap_mode("plot")tmap mode set to plotting
- We perform some simple stats to count the total number of filtered hexagons, and to see the maximum number of bus stops in a hexagon.
- Unlike Take-Home Exercise 1, the number of hexagons have decreased, and the maximum number of bus stops per hexagon is lower.
show code
# NB: Code reused from my own take-home exercise 1
cat(paste("Total number of raw hexagons is\t\t\t: ", nrow(raw_hex_grid), "\n"))Total number of raw hexagons is : 8843
show code
cat(paste("Total number of hexagons (n_bus_stop > 1) is\t: ", nrow(hexagon_sf)), "\n")Total number of hexagons (n_bus_stop > 1) is : 2172
show code
cat("\nPrinting map_hexagon_sf:\n >> ")
Printing map_hexagon_sf:
>>
show code
hexagon_sf[hexagon_sf$n_bus_stops > 5, ]Simple feature collection with 47 features and 2 fields
Geometry type: POLYGON
Dimension: XY
Bounding box: xmin: 10532.62 ymin: 29837.95 xmax: 42782.62 ymax: 47807.98
Projected CRS: SVY21 / Singapore TM
First 10 features:
grid_id n_bus_stops raw_hex_grid
149 149 6 POLYGON ((10720.12 34059.82...
170 170 6 POLYGON ((11470.12 34059.82...
191 191 6 POLYGON ((12032.62 35683.62...
214 214 6 POLYGON ((12595.12 36008.38...
217 217 6 POLYGON ((12595.12 39255.98...
297 297 6 POLYGON ((14282.62 35034.1,...
347 347 7 POLYGON ((15782.62 34384.58...
405 405 6 POLYGON ((17470.12 39905.49...
426 426 6 POLYGON ((17845.12 39905.49...
441 441 6 POLYGON ((18032.62 40230.25...
- For the next step, we’ll need to manage the aspatial bus trips dataset, which is what we’ll work on now.
1.5 Aspatial Data Wrangling: Bus trip dataset
1.5.1 Import Bus O/D Dataset
For our purposes, we will focus only on 2023-October Passenger Volume by Origin Destination Bus Stops, downloaded from LTA DataMall;
We use
read_csv()to load the data from the .csv file;We use
select()with a-sign to remove two columns redundant for our analysis:$PT_TYPEcolumn indicates the type of public transport, however, every value is “BUS”$YEAR_MONTHcolumn similarly has “2023-10” for every value, which we are aware of- With this in mind, we drop these two columns to save space.
Finally, we use
mutate_at()to convert two columns ($ORIGIN_PT_CODEand$DESTINATION_PT_CODE)from character to factor, for easier analysis.We use
str()to check the columns, datatypes, and number of rows:
show code
odbus_2310 <- read_csv("data/aspatial/origin_destination_bus_202310.csv") %>%
select( -PT_TYPE, -YEAR_MONTH) %>%
mutate_at(c("ORIGIN_PT_CODE", "DESTINATION_PT_CODE"), as.factor)Rows: 5694297 Columns: 7
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (5): YEAR_MONTH, DAY_TYPE, PT_TYPE, ORIGIN_PT_CODE, DESTINATION_PT_CODE
dbl (2): TIME_PER_HOUR, TOTAL_TRIPS
ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
show code
str(odbus_2310)tibble [5,694,297 × 5] (S3: tbl_df/tbl/data.frame)
$ DAY_TYPE : chr [1:5694297] "WEEKENDS/HOLIDAY" "WEEKDAY" "WEEKENDS/HOLIDAY" "WEEKDAY" ...
$ TIME_PER_HOUR : num [1:5694297] 16 16 14 14 17 17 17 7 14 14 ...
$ ORIGIN_PT_CODE : Factor w/ 5073 levels "01012","01013",..: 105 105 4428 4428 2011 834 834 781 4462 4462 ...
$ DESTINATION_PT_CODE: Factor w/ 5077 levels "01012","01013",..: 240 240 4742 4742 693 809 809 235 4002 4002 ...
$ TOTAL_TRIPS : num [1:5694297] 3 5 3 5 4 1 24 2 1 7 ...
- This is a huge
tibbledataframe with over 5 million rows, so we will filter this now by peaks; - For this study, we focus on Weekday afternoon peak
1.5.2 Filter For Peaks – Weekday Afternoon
- We now perform a multi-step filter process;
- We combine
mutate()withcase_when()to create a new column,$PEAK, based on the study criteria:- We set the value to “WEEKDAY_AFTERNOON_PEAK” if
$DAY_TYPEis “WEEKDAY” and bus tap-on time (e.g.$TIME_PER_HOUR) is between 5 pm and 8pm, inclusive;- Note that we convert the values for
$TIME_PER_HOURto 24-hour clock, e.g. “5pm” is “17” hundred hours, “8pm” is “20” hundred hours.
- Note that we convert the values for
- For all remaining values, we assign an “Unknown” value.
- We set the value to “WEEKDAY_AFTERNOON_PEAK” if
- We then use
filter()to eliminate those with “Unknown”$PEAKvalues, i.e. rows outside the period of interest for the study - We use
group_by()to group the values by$ORIGIN_PT_CODEand$DESTINATION_PT_CODE, and usesummarise()to aggregate the sum of$TOTAL_TRIPSas a new column,$TRIPS. - We use
write_rds()to save the output dataframe,odbus_filtered, as an RDS object for future reference/load.
- We combine
odbus_filtered <- odbus_2310 %>%
mutate(PEAK = case_when(
DAY_TYPE == "WEEKDAY" & TIME_PER_HOUR >= 17 & TIME_PER_HOUR <= 20 ~ "WEEKDAY_AFTERNOON_PEAK",
TRUE ~ "Unknown"
)) %>%
filter(
case_when(
PEAK == "Unknown" ~ FALSE,
TRUE ~ TRUE
)) %>%
group_by(ORIGIN_PT_CODE, DESTINATION_PT_CODE) %>%
summarise(TRIPS = sum(TOTAL_TRIPS))`summarise()` has grouped output by 'ORIGIN_PT_CODE'. You can override using
the `.groups` argument.
write_rds(odbus_filtered, "data/rds/odbus_filtered_weekday.rds")
head(odbus_filtered)# A tibble: 6 × 3
# Groups: ORIGIN_PT_CODE [1]
ORIGIN_PT_CODE DESTINATION_PT_CODE TRIPS
<fct> <fct> <dbl>
1 01012 01112 540
2 01012 01113 516
3 01012 01121 303
4 01012 01211 363
5 01012 01311 630
6 01012 01549 6
1.6 Combine Bus Trip Data With hexagon_sf Dataframe
- For our study purposes, we need to have the number of bus trips originating from each hexagon. In order to achieve this, we must combine our three current dataframes:
hexagon_sf, ansfdataframe with$grid_idcolumn (primary key) and the specific polygon geometry of each hexagon;bus_stop_sf, ansfdataframe with the$BUS_STOP_N(primary key) and the point geometry of each bus stop;odbus_filtered, atibbledataframe with the$ORIGIN_PT_CODE(primary key) column and the trip details for each of the four peak periods of interest.
1.6.1 bus_stop_hexgrid_id: Identify Hexagon grid_id For Each Bus Stop
- First, we combine
hexagon_sfwithsg_bus_stop_sf;- We use
st_intersectionto combine the dataframes such that each row ofsg_bus_stop_sfhas an associatedgrid_id; - We use
select()to filter the resultantbus_stop_hexgrid_iddataframe to only$grid_idand$BUS_STOP_Ncolumns, and usest_drop_geometry()to convert into a simple dataframe with just two columns:
- We use
show code
bus_stop_hexgrid_id <- st_intersection(bus_stop_sf, hexagon_sf) %>%
select(BUS_STOP_N, grid_id) %>%
st_drop_geometry()Warning: attribute variables are assumed to be spatially constant throughout
all geometries
show code
cat("\nNumber of bus stops\t:", length(unique(bus_stop_hexgrid_id$BUS_STOP_N)))
Number of bus stops : 5140
show code
cat("\nNumber of hexgrids\t:", length(unique(bus_stop_hexgrid_id$grid_id)))
Number of hexgrids : 2170
show code
head(bus_stop_hexgrid_id) BUS_STOP_N grid_id
3265 25059 1
3265.1 25059 2
2566 25751 3
254 26379 4
2399 26369 5
2893 25761 6
- Eagle-eyed readers may notice that BUS_STOP_N #25059 is in both
$grid_id1 & 2; - Let’s check if there’s any other duplicates:
show code
bus_stop_hexgrid_id$BUS_STOP_N[duplicated(bus_stop_hexgrid_id$BUS_STOP_N)][1] "25059"
- Only BUS_STOP_N #25059 is duplicated; let’s see why this is:
show code
tmap_mode("view")tmap mode set to interactive viewing
show code
tm_shape(hexagon_sf[hexagon_sf$grid_id %in% c(1, 2),]) +
tm_polygons(col = "grid_id", palette = "Spectral") +
tm_shape(bus_stop_sf[bus_stop_sf$BUS_STOP_N %in% c(25059),]) +
tm_dots()show code
tmap_mode("plot")tmap mode set to plotting
- It appears that BUS_STOP_N #25059 is exactly on the boundary between the two hexagons.
- Here we perform simple manual intervention data cleaning, declaring the bus stop is in
$grid_id2 by deleting the first row;- We use
subset()to select values of$grid_idthat are not equal to 1
- We use
show code
bus_stop_hexgrid_id <- subset(bus_stop_hexgrid_id, grid_id != 1)
cat("\nNumber of bus stops\t:", length(unique(bus_stop_hexgrid_id$BUS_STOP_N)))
Number of bus stops : 5140
show code
cat("\nNumber of hexgrids\t:", length(unique(bus_stop_hexgrid_id$grid_id)))
Number of hexgrids : 2169
show code
cat("\n\nPrinting rows with duplicated bus stop values\t:", bus_stop_hexgrid_id$BUS_STOP_N[duplicated(bus_stop_hexgrid_id$BUS_STOP_N)])
Printing rows with duplicated bus stop values :
show code
cat("\n\n(If empty, it worked!)")
(If empty, it worked!)
- Now we append hexagon code onto
odbus_filtered. We do this in two steps; - First, we use
left_join()to add the hexagon$grid_idbyBUS_STOP_Nnumber;- We use
rename()to rename columns, and specify the origin bus stop and origin hex grid id asORIGIN_BSandORIGIN_HEXrespectively; - We create a
duplicatetibble data.frame to check for duplicate results, and luckily we see an empty tibble
- We use
show code
od_data <- left_join(odbus_filtered , bus_stop_hexgrid_id,
by = c("ORIGIN_PT_CODE" = "BUS_STOP_N")) %>%
rename(ORIGIN_BS = ORIGIN_PT_CODE,
ORIGIN_HEX = grid_id)
duplicate <- od_data %>%
group_by_all() %>%
filter(n()>1) %>%
ungroup()
duplicate# A tibble: 0 × 4
# ℹ 4 variables: ORIGIN_BS <chr>, DESTINATION_PT_CODE <fct>, TRIPS <dbl>,
# ORIGIN_HEX <int>
show code
# od_data[!complete.cases(od_data), ]
#
# bus_stop_hexgrid_id[]
# hexagon_sf[hexagon_sf$grid_id %in% c(1, 2),]
# bus_stop_hexgrid_id[bus_stop_hexgrid_id$BUS_STOP_N %in% c(03361),]
#
# raw_bus_stop_sf[raw_bus_stop_sf$BUS_STOP_N %in% c(03361, 03549, 03579, 59009),]- Now we repeat the step, appending the destination hex ID
show code
od_data <- left_join(od_data , bus_stop_hexgrid_id,
by = c("DESTINATION_PT_CODE" = "BUS_STOP_N")) %>%
rename(DESTIN_BS = DESTINATION_PT_CODE,
DESTIN_HEX = grid_id)
duplicate <- od_data %>%
group_by_all() %>%
filter(n()>1) %>%
ungroup()
duplicate# A tibble: 0 × 5
# ℹ 5 variables: ORIGIN_BS <chr>, DESTIN_BS <chr>, TRIPS <dbl>,
# ORIGIN_HEX <int>, DESTIN_HEX <int>
show code
# od_data[!complete.cases(od_data), ]- Once again, we have an empty tibble.
- We finally create the final version of our flow dataset.
- Just to be safe, we perform a step to remove duplicates using
unique() drop_na()removes bus stops for which we have no info. It turns out there are bus stop numbers outside our bus stop dataset, like 03361, 03549, 03579, 59009;- We use
group_by()to combine rows with the same$ORIGIN_HEXand$DESTIN_HEX, and aggregate the number of trips withsummarise()
- Just to be safe, we perform a step to remove duplicates using
show code
od_data <- od_data %>%
unique() %>%
drop_na() %>%
group_by(ORIGIN_HEX, DESTIN_HEX) %>%
summarise(SUM_TRIPS = sum(TRIPS))`summarise()` has grouped output by 'ORIGIN_HEX'. You can override using the
`.groups` argument.
show code
head(od_data)# A tibble: 6 × 3
# Groups: ORIGIN_HEX [1]
ORIGIN_HEX DESTIN_HEX SUM_TRIPS
<int> <int> <dbl>
1 2 6 3
2 2 13 34
3 2 20 182
4 2 37 1
5 2 50 18
6 2 53 1
- Now we write the output to RDS
show code
write_rds(od_data, "data/rds/od_data.rds")
od_data <- read_rds("data/rds/od_data.rds")- Remove intrazonal flows
show code
od_data1 <- od_data[od_data$ORIGIN_HEX!=od_data$DESTIN_HEX,]- Create desire lines
show code
flowLine <- od2line(flow = od_data1,
zones = hexagon_sf,
zone_code = "grid_id")Creating centroids representing desire line start and end points.
show code
summary(od_data1$SUM_TRIPS) Min. 1st Qu. Median Mean 3rd Qu. Max.
1.0 4.0 17.0 129.6 66.0 73720.0
tmap_mode("plot")tmap mode set to plotting
tm_shape(hexagon_sf) +
tm_polygons() +
flowLine %>%
filter(SUM_TRIPS >= 1000) %>%
tm_shape() +
tm_lines(lwd = "SUM_TRIPS",
style = "quantile",
scale = c(0.1, 1, 3, 5, 7, 10),
n = 6,
alpha = 0.3)
1.6.2 Identify Bus Trip Details For Each Hexagon grid_id
- Here, we again use multiple steps to generate bus trip details for each hexagon
grid_id;- We use
left_join()to add thegrid_idto each row ofodbus_filtered, since each row has a unique single bus stop ID (i.e.$BUS_STOP_N); - We use
select()to retain only thegrid_idand the four peak-trips columns; - We combine
group_by()andsummarise()to aggregate the trips for each peak bygrid_id.
- We use
- Finally, we use
head()to preview thegrid_trips_dftibble dataframe.
show code
colnames(odbus_filtered)[1] "ORIGIN_PT_CODE" "DESTINATION_PT_CODE" "TRIPS"
show code
grid_trips_df <- left_join(odbus_filtered, bus_stop_hexgrid_id,
by = c("ORIGIN_PT_CODE" = "BUS_STOP_N")) %>%
select(grid_id,
TRIPS) %>%
group_by(grid_id) %>%
summarise(
TRIPS = sum(TRIPS)
)Adding missing grouping variables: `ORIGIN_PT_CODE`
show code
head(grid_trips_df)# A tibble: 6 × 2
grid_id TRIPS
<int> <dbl>
1 2 390
2 3 114
3 4 291
4 5 241
5 6 1905
6 7 299
1.6.3 Combine Bus Trip Details Back Into hexagon_sf
- Finally, it’s time to recombine bus trip data back into
hexagon_sf;- We use
left_joinon$grid_idto add trip data back into hexagon_sf; - We add a failsafe
mutate()to replace any “NA” values for the columns.
- We use
show code
hexagon_sf <- left_join(hexagon_sf, grid_trips_df,
by = 'grid_id' ) %>%
mutate(
TRIPS = ifelse(is.na(TRIPS), 0, TRIPS)
)
head(hexagon_sf)Simple feature collection with 6 features and 3 fields
Geometry type: POLYGON
Dimension: XY
Bounding box: xmin: 3595.122 ymin: 27889.39 xmax: 4907.622 ymax: 31570
Projected CRS: SVY21 / Singapore TM
grid_id n_bus_stops TRIPS raw_hex_grid
1 1 1 0 POLYGON ((3782.622 27889.39...
2 2 1 390 POLYGON ((4157.622 27889.39...
3 3 1 114 POLYGON ((4532.622 28538.91...
4 4 1 291 POLYGON ((4532.622 30487.47...
5 5 1 241 POLYGON ((4532.622 31136.99...
6 6 1 1905 POLYGON ((4720.122 28214.15...
1.7 Exploratory Data Analysis Of Bus Trips, Across Peak Periods, By Hexagons
- For
ggplot, we need data in long format, so we can usegather()ongrid_trips_dffrom Section 1.6.2 to pivot this; - We then pipe this into a
geom_boxplot()for an exploratory look:
show code
# gather(grid_trips_df, key = "Peak", value = "Trips", -grid_id) %>%
# ggplot( aes(x=grid_id, y='TRIPS', fill=grid_id)) +
# geom_boxplot() +
# ggtitle("Boxplot: Trips over peak periods, 2023-Oct data") +
# xlab("") +
# theme(
# legend.position="none"
# ) +
# coord_flip()We also observe that number of trips for Weekday Morning & Weekday Afternoon seems to be larger than Weekend Morning and Weekend Evening peak trips. This is also confirmed by the figure in the next section.
This means that we will have to consider Weekday and Weekend peaks on different scales.
- This is an exceptionally ugly plot, but it shows an important point: there is some serious right skew in our dataset;
- Clearly, there are some hexagons with exceptionally high trips compared to the rest of the hexagons But, could this be because some hexagons have up to 11 bus stops, while others have 1 or 2?
- We do a quick scatter plot based on
$n_bus_stopsto verify this:
show code
# hexagon_sf %>%
# st_drop_geometry() %>%
# pivot_longer(cols = starts_with("WEEK"),
# names_to = "PEAK", values_to = "TRIPS") %>%
# ggplot( aes(x=TRIPS, y=n_bus_stops, color=PEAK, shape=PEAK)) +
# geom_point(size=2) +
# ggtitle("Scatterplot: Trips over peak periods by number of bus stops per hexagon, 2023-Oct data") +
# theme(legend.position=c(.85, .15),
# legend.background = element_rect(fill = "transparent"),
# legend.key.size = unit(0.5, "cm"),
# legend.text = element_text(size = 6),
# legend.title = element_text(size = 8)
# ) - Surprising results from our plot! If we consider those with > 100,000 trips as outliers, most of them come from hexagons with between 4-8 bus stops;
- There is some correlation between number of bus stops and high numbers of trips, but a stronger factor is peak time; Weekday Morning peak trips, followed by Weekday Afternoon peak trips, contribute to the largest outliers.
I note that these visualizations only scrape the surface of understanding the data. However, this is not the focus of our study; we do these quick visualizations only to provide better context for our study.